package com.wzw.shoppingcart.resolver;

import com.wzw.shoppingcart.entity.Cart;
import com.wzw.shoppingcart.entity.CartLine;
import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.service.CartLineService;
import com.wzw.shoppingcart.service.CartService;
import com.wzw.shoppingcart.service.ProductService;
import graphql.kickstart.tools.GraphQLQueryResolver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 *@author wzw
 * 2023/4/8
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class CartQueryResolver implements GraphQLQueryResolver {
    private final CartLineService cartLineService;
    private final CartService cartService;
    private final ProductService productService;


    public Cart getCartByUserId(Integer userId) {
        Cart cart = new Cart();
        List<CartLine> cartLines = cartLineService.getCartLines(userId);
        if (cartLines.isEmpty()) {
            return cart;
        }

        cartLines.forEach(c->c.setProduct(productService.getProductById(c.getProductId())));

        cart.setCartLines(cartLines);
        BigDecimal totalOriginPrice = cartService.calculateTotalPrice(cartLines);
        cart.setTotalOriginPrice(totalOriginPrice);
        BigDecimal totalDiscountPrice=cartService.calculateDiscount(cartLines,totalOriginPrice);
        cart.setTotalDiscountPrice(totalDiscountPrice);

        List<Product> productList = cartLineService.getProducts(cartLines);
        productService.setDiscountType(productList);

        return cart;
    }

}
